import * as chitu from "maishu-chitu";
import { ShoppingService } from "services/shopping";
import React = require("react");
import { FormValidator, rules } from "maishu-dilu";
import { ui } from "jquery";
import { formatDate } from "mobile/site";
import ReactDOM = require("react-dom");
import { DataSource, BoundField, CustomField, GridViewCell, GridView } from "maishu-wuzhui";
import { createGridView } from "maishu-wuzhui-helper";
import { buttonOnClick, showDialog, hideDialog } from "maishu-ui-toolkit";
import { PageProps } from "maishu-chitu-react";


// export default function (page: chitu.Page) {



//     ReactDOM.render(<CouponCodeListPage />, page.element);

// }

// 

type Status = 'all' | 'used' | 'canUse' | 'expired';
interface PageState {
    coupons: Array<Coupon>,
    status: Status,
}

export default class CouponCodeListPage extends React.Component<PageProps, PageState>{
    private couponsSelect: HTMLSelectElement;
    private countInput: HTMLInputElement;
    private couponCodesTable: HTMLTableElement;
    // private currentStatus: Status = 'all';
    private dataSource: DataSource<CouponCode>;
    private dialogElement: HTMLElement;
    private validator: FormValidator;
    gridView: GridView<CouponCode>;
    shopping: ShoppingService;

    constructor(props) {
        super(props);
        this.state = { coupons: [], status: "all" };

        this.shopping = this.props.createService(ShoppingService);

    }
    switchTab(status: Status) {
        if (status == this.state.status)
            return;

        switch (status) {
            case 'all':
                this.gridView.selectArguments.filter = null;
                break;
            case 'used':
                this.gridView.selectArguments.filter = 'UsedDateTime <> null';
                break;
            case 'canUse':
                this.gridView.selectArguments.filter = `UsedDateTime == null and DateTime.Now.Date <= ValidEnd`;
                break;
            case 'expired':
                this.gridView.selectArguments.filter = `UsedDateTime == null and DateTime.Now.Date > ValidEnd`;
                break;
        }
        this.dataSource.select(this.gridView.selectArguments);
        this.setState({ status })
    }

    status(couponCode: CouponCode) {

        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth();
        var yyyy = today.getFullYear();
        var currentDate = new Date(yyyy, mm, dd);

        var text;
        var status;
        if (couponCode.UsedDateTime) {
            status = 'used';
            text = '已使用';
        }
        else if (currentDate > couponCode.ValidEnd) {
            status = 'expired';
            text = '已过期';
        }
        else {
            status = 'valid';
            text = '可使用';
        }

        return { value: status, text };
    }
    showGenerateDialog() {
        this.validator.clearErrors();
        showDialog(this.dialogElement);
    }
    async generateCouponCode(): Promise<any> {
        let isValid = await this.validator.check();
        if (isValid == false) {
            return Promise.reject({});
        }
        let couponId = (this.dialogElement['coupon'] as HTMLSelectElement).value;
        let count = Number.parseInt((this.dialogElement['count'] as HTMLInputElement).value);
        return this.shopping.generateCouponCode(couponId, count).then(() => {
            hideDialog(this.dialogElement);
            return this.dataSource.select();
        });
    }
    componentDidMount() {
        // this.validator = new FormValidator(this.dialogElement, {
        //     count: { rules: ['required'], display: '数量' },
        //     coupon: { rules: ['required'], messages: { required: '请选择优惠劵' } }//
        // });

        this.shopping.coupons({}).then(r => {
            // this.state.coupons = r.dataItems;
            // this.setState(this.state);
            this.setState({ coupons: r.dataItems });
        });

        let { required } = rules;
        // let e = this.dialogElement;
        this.validator = new FormValidator(this.dialogElement,
            { name: "count", rules: [required('请输入数量')] },
            { name: "coupon", rules: [required('请选择优惠劵')] }
        );

        this.dataSource = new DataSource({
            primaryKeys: ["Id"],
            select: (args) => {
                return this.shopping.couponCodes(args);
            }
        })
        let self = this;
        this.gridView = createGridView<CouponCode>({
            element: this.couponCodesTable,
            dataSource: this.dataSource,
            columns: [
                new BoundField({ dataField: 'Title', headerText: '名称' }),
                new BoundField({ dataField: 'Code', headerText: '优惠码' }),
                new CustomField({
                    createItemCell(data: CouponCode) {
                        let cell = new GridViewCell();
                        cell.element.innerHTML = `${formatDate(data.ValidBegin)} - ${formatDate(data.ValidEnd)}`;
                        return cell;
                    },
                    headerText: '有效期',
                    headerStyle: { width: '200px' } as CSSStyleDeclaration,
                    itemStyle: { textAlign: 'center' } as CSSStyleDeclaration
                }),
                new BoundField({
                    dataField: 'UsedDateTime', headerText: '使用时间', dataFormatString: '{g}'
                }),
                new CustomField({
                    createItemCell(dataItem: CouponCode) {
                        let cell = new GridViewCell();
                        let status = self.status(dataItem);
                        ReactDOM.render(
                            <button className="btn btn-minier btn-info" disabled={status.value != 'valid'}>{status.text}</button >, cell.element);
                        return cell;
                    },
                    headerText: '状态',
                    headerStyle: { textAlign: 'center', width: '100px' } as CSSStyleDeclaration,
                    itemStyle: { textAlign: 'center' } as CSSStyleDeclaration
                })
            ]
        })
    }
    render() {
        let coupons = this.state.coupons || [];
        let status = this.state.status;
        return (
            <div>
                <div className="tabbable">
                    <ul className="nav nav-tabs">
                        <li className={status == "all" ? "active" : null}>
                            <a data-toggle="tab" onClick={() => this.switchTab('all')}>全部</a>
                        </li>
                        <li className={status == "canUse" ? "active" : null}>
                            <a data-toggle="tab" onClick={() => this.switchTab('canUse')}>可使用</a>
                        </li>
                        <li className={status == "used" ? "active" : null}>
                            <a data-toggle="tab" onClick={() => this.switchTab('used')}>已使用</a>
                        </li>
                        <li className={status == "expired" ? "active" : null}>
                            <a data-toggle="tab" onClick={() => this.switchTab('expired')}>已过期</a>
                        </li>
                        <li className="pull-right">
                            <button className="btn btn-sm btn-primary">
                                <i className="icon-download-alt"></i>
                                <span>导出</span>
                            </button>
                        </li>
                        <li className="pull-right">
                            <button className="btn btn-sm btn-primary"
                                ref={(o: HTMLButtonElement) => {
                                    if (!o) return;
                                    o.onclick = () => this.showGenerateDialog();

                                }}>
                                <i className="icon-cog"></i>
                                <span>生成优惠码</span>
                            </button>
                        </li>

                        <li className="pull-right">
                            <button id="btnSearch" data-bind="click: search" className="btn btn-sm btn-primary">
                                <i className="icon-search"></i>
                                <span>查找</span>
                            </button>
                        </li>
                        <li className="pull-right">
                            <input data-bind="value: filter.searchText" id="txtSearch" className="nav-search-input form-control" type="text"
                                placeholder="输入要查找的优惠码或优惠券编号" style={{ width: 300 }} />
                        </li>
                    </ul>
                </div>
                <table ref={(o: HTMLTableElement) => this.couponCodesTable = o || this.couponCodesTable}></table>
                <form className="modal fade in" ref={(o: HTMLElement) => this.dialogElement = o || this.dialogElement}>
                    <div className="modal-dialog">
                        <div className="modal-content">
                            <div className="modal-header">
                                <button type="button" className="close" data-dismiss="modal">
                                    <span aria-hidden="true">&times;</span>
                                    <span className="sr-only">Close</span>
                                </button>
                                <h4 className="modal-title">生成优惠码</h4>
                            </div>
                            <div className="modal-body form-horizontal">
                                <div className="form-group">
                                    <label className="col-sm-2 control-label">
                                        优惠劵
                                    </label>
                                    <div className="col-sm-10">
                                        <select name="coupon" className="form-control"
                                            ref={(e: HTMLSelectElement) => this.couponsSelect = e || this.couponsSelect}>
                                            <option value="">请选择优惠劵</option>
                                            {coupons.map(o =>
                                                <option key={o.Id} value={o.Id}>
                                                    {o.Title}
                                                </option>
                                            )}
                                        </select>
                                    </div>
                                </div>
                                <div className="form-group">
                                    <label className="col-sm-2 control-label">
                                        数量
                                    </label>
                                    <div className="col-sm-10">
                                        <input name="count" type="text" className="form-control" placeholder="请输入生成优惠码的数量"
                                            ref={(e: HTMLInputElement) => this.countInput = e || this.countInput} />
                                    </div>
                                </div>
                            </div>
                            <div className="modal-footer">
                                <button type="button" className="btn btn-default" data-dismiss="modal">取消</button>
                                <button type="button" className="btn btn-primary"
                                    ref={(o: HTMLButtonElement) => {
                                        if (!o) return;
                                        o.onclick = buttonOnClick(() => this.generateCouponCode());
                                    }}>确认</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        );
    }
}